/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.load {
	
	import lads.flad.interfaces.ILoadable;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	
	/**
	 * SoundLoader: A wrapper class for preloading sounds.
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class SoundLoader extends EventDispatcher implements ILoadable {
		
		private var _sound			:Sound;
		private var _loadCompleted	:Boolean;
		private var _url			:String;
		private var _name			:String;
		
		public function SoundLoader() {
			
		}
		
		public function load($url:String = null):void {
			_url = $url || _url;
			_sound = new Sound();
			_sound.addEventListener(Event.COMPLETE, loadComplete);
			_sound.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			_sound.load(new URLRequest(_url));
		}
		
		private function loadComplete(e:Event):void {
			_loadCompleted = true;
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function loadError(e:Event):void {
			throw new Error("SoundLoader could not load " + _url);
		}
		
		public function get loadPercent():Number {
			return _sound ? _sound.bytesLoaded / _sound.bytesTotal : 0;
		}
		
		public function get loadCompleted():Boolean {
			return _loadCompleted;
		}
		
		public function get name():String { return _name; }
		public function set name(value:String):void {
			_name = value;
		}
		
		public function get url():String { return _url; }
		public function set url(value:String):void {
			_url = value;
		}
		
		public function get sound():Sound { return _sound; }
		
	}

}